<?php
defined('_VISIT_URL_') or exit('No direct script access allowed');

class housecraft {

	//获取家政服务列表
	public function getHousecraftList() {
		$status = getPost('status');
		$sortation = getPost('sortation');
		$istop = getPost('istop');
		$keyword = getPost('keyword');
		$page = getPost('page', '1');
		$permission = getPost('permission');

		$queryitem = '';
		if ($status != '')
			$queryitem .= ' and status = ' . $status;
		if ($sortation != '')
			$queryitem .= ' and sortation = ' . $sortation;
		if ($istop != '')
			$queryitem .= ' and istop = ' . $istop;
		if ($keyword != '')
			$queryitem .= " and title like '%" . $keyword . "%'";

		$limititem = ' limit ' . ($page - 1) * 50 . ', 50';
		$sortOption = 'refreshtime desc, id desc';

		$rst = new sqlcon();

		$info = $rst->getInfo('count(*) as num', 'housecraft', 'id != 0' . $queryitem);

		$list = $rst->getList('housecraftid, title, company_verifyid, sortation, person, phone, identity, feature, area, click, dial, istop, status, expiretime, topendtime', 'housecraft', 'id != 0' . $queryitem, $sortOption . $limititem);
		for ($i = 0; $i < count($list); $i++) {
			$nowtime = strtotime(date('Y-m-d H:i:s'));
			//计算展示剩余天数
			$day = 0;
			$expiretime = strtotime($list[$i]['expiretime']);
        	$seconds = $expiretime - $nowtime;
        	if ($seconds >= 0) {
        		$day = $seconds / 60 / 60 / 24;
        	}
        	$list[$i]['showResidueDays'] = intval($day);

			//计算置顶剩余天数
			$day = 0;
			if ($list[$i]['istop'] == '1') {
				$topendtime = strtotime($list[$i]['topendtime']);
				$seconds = $topendtime - $nowtime;
				if ($seconds >= 0) {
	        		$day = $seconds / 60 / 60 / 24;
	        	}
			}
			$list[$i]['topResidueDays'] = intval($day);

			//格式化到期时间
			if ($list[$i]['expiretime'] > '2034-01-01 00:00:00') {
				$list[$i]['expiretime'] = '永久';
			}
		}

		$result = util::getSuccess('success');
	    $result['listCount'] = $info['num'];
	    $result['allPages'] = util::getListPage($info['num'], 50);
	    $result['housecraftList'] = $list;
	    $result['rowCount'] = 50;
	    if ($permission == 'yes') {
	    	$result['permission'] = util::getOperateItem(getPost('menuid'));
	    }
		return $result;
	}

	//保存家政服务信息
	public function saveHousecraft() {
		if (getPost('flag') != 'add' && getPost('flag') != 'edit') {
			return util::getValidError('保存操作标识异常');
		}

		if (empty(getPost('title')) || valid::isWicked(getPost('title'))) {
			return util::getValidError('标题格式异常');
		}

		if (getPost('sortation') == '') {
			return util::getValidError('请选择栏目分类');
		}

		if (!empty(getPost('address')) && valid::isWicked(getPost('address'))) {
			return util::getValidError('商家地址格式异常');
		}

		if (empty(getPost('person')) || valid::isWicked(getPost('person'))) {
			return util::getValidError('联系人格式异常');
		}

		if (empty(getPost('phone')) || (!valid::isMobile(getPost('phone')) && !valid::isTelphone(getPost('phone')))) {
			return util::getValidError('联系电话格式异常');
		}

		if (!empty(getPost('remark')) && valid::isWicked(getPost('remark'))) {
			return util::getValidError('备注格式异常');
		}

		if (getPost('sortation') == '0' && getPost('identity') == '') {
			return util::getValidError('月嫂保姆类必须选择服务者身份');
		}

		if (empty(getPost('introduce'))) {
			return util::getValidError('请填写服务详情');
		}

		$rst = new sqlcon();
		$uuid = '';

		if (getPost('flag') == 'add') {
			if (empty(getPost('expiretime'))) {
				return util::getValidError('请填写到期时间');
			}

			$uuid = util::getUUID();

			//写入服务详情
			$introducePath = 'upload/housecraft/introduce/' . $uuid . '.txt';
			$introduceFile = $uuid . '.txt';
			util::writeFile('upload/housecraft/introduce', $introduceFile, getPost('introduce'));

			//保存列表小图
	        $smallPath = '';
	        if (strpos(getPost('smallpic'), ';base64,')) {
	            $smallPath = 'upload/housecraft/samplepic/' . util::getFileName(getPost('smallpic'));
	            util::saveFile(getPost('smallpic'), _IMGS_PATH_ . $smallPath);
	        }

	        //格式化服务特征的分隔逗号
	        $feature = getPost('feature');
	        if (!empty($feature)) {
	        	$feature = str_replace('，', ',', $feature);
				$lastStr = substr($feature, -1);
				if ($lastStr == ',' || $lastStr == '，') {
					$feature = substr($feature, 0, -1);
				}
				$feature = str_replace(',', '，', $feature);
	        }

	        //保存详情大图
	        $bigPicList = json_decode($_POST['bigpic'], true)[0];
	        $tempPicPath = array();
	        foreach ($bigPicList as $value) {
	        	$tempPath = '';
	        	if (strpos($value, ';base64,')) {
	        		$tempPath = 'upload/housecraft/samplepic/' . util::getFileName($value);
		            util::saveFile($value, _IMGS_PATH_ . $tempPath);
		            $tempPicPath[] = $tempPath;
	        	}
	        }

	        //保存图片记录
	        for ($i = 0; $i < count($tempPicPath); $i++) {
	        	$rst->addCollect('housecraftid', $uuid);
	        	$rst->addCollect('path', $tempPicPath[$i]);
	        	$rst->addCollect('sx', $i + 1);
	        	$rst->insertInfo('housecraftpic');
	        }

	        //保存信息
			$rst->addCollect('housecraftid', $uuid);
			$rst->addCollect('title', getPost('title'));
			$rst->addCollect('company_verifyid', '');
			$rst->addCollect('sortation', getPost('sortation'));
			$rst->addCollect('businessid', '');
			$rst->addCollect('business', '');
			$rst->addCollect('address', getPost('address'));
			$rst->addCollect('position', getPost('position'));
			$rst->addCollect('person', getPost('person'));
			$rst->addCollect('phone', getPost('phone'));
			$rst->addCollect('identity', getPost('identity'));
			$rst->addCollect('feature', $feature);
			$rst->addCollect('area', getPost('area'));
			$rst->addCollect('introduce', $introducePath);
			$rst->addCollect('smallpic', $smallPath);
			$rst->addCollect('browse', '0');
			$rst->addCollect('click', '0');
			$rst->addCollect('dial', '0');
			$rst->addCollect('istop', '0');
			$rst->addCollect('toptype', '0');
			$rst->addCollect('refreshcount', '0');
			$rst->addCollect('isautorefresh', '0');
			$rst->addCollect('status', getPost('status'));
			$rst->addCollect('sort', '0');
			$rst->addCollect('clicktime', '');
			$rst->addCollect('dialtime', '');
			$rst->addCollect('refreshtime', date('Y-m-d H:i:s'));
			$rst->addCollect('expiretime', getPost('expiretime') . ' ' . date('H:i:s'));
			$rst->addCollect('topstarttime', '');
			$rst->addCollect('topendtime', '');
			$rst->addCollect('remark', getPost('remark'));
			$rst->insertInfo('housecraft');
		}
		else {
			if (empty(getPost('housecraftid'))) {
				return util::getValidError('ID格式错误');
			}

			$uuid = getPost('housecraftid');

			//写入服务详情
			$introducePath = 'upload/housecraft/introduce/' . $uuid . '.txt';
			$introduceFile = $uuid . '.txt';
			util::writeFile('upload/housecraft/introduce', $introduceFile, getPost('introduce'));

			//保存列表小图
	        $smallPath = '';
	        if (strpos(getPost('smallpic'), ';base64,')) {
	            $smallPath = 'upload/housecraft/samplepic/' . util::getFileName(getPost('smallpic'));
	            util::saveFile(getPost('smallpic'), _IMGS_PATH_ . $smallPath);

	            //删除原先的列表小图
	            $info = $rst->getInfo('smallpic', 'housecraft', "housecraftid = '" . getPost('housecraftid') . "'");
	            if (!empty($info['smallpic'])) {
	            	$file_path = _IMGS_PATH_ . $info['smallpic'];
					if (file_exists($file_path)) {
						unlink($file_path);
					}
	            }
	        }
	        else {
	            $smallPath = str_replace(_HTTP_PATH_, '', getPost('smallpic'));
	        }

	        //格式化服务特征的分隔逗号
	        $feature = getPost('feature');
	        if (!empty($feature)) {
	        	$feature = str_replace('，', ',', $feature);
				$lastStr = substr($feature, -1);
				if ($lastStr == ',' || $lastStr == '，') {
					$feature = substr($feature, 0, -1);
				}
				$feature = str_replace(',', '，', $feature);
	        }

	        //取出原产品中所有的详情大图路径，若本次保存时已不存在，则删除
	        $list = $rst->getList('id, path', 'housecraftpic', "housecraftid = '" . getPost('housecraftid') . "'");
	        $bigPicList = json_decode($_POST['bigpic'], true)[0];
	        for ($i = 0; $i < count($list); $i++) {
				$isDel = 'yes';
				foreach ($bigPicList as $value) {
					if (_HTTP_PATH_ . $list[$i]['path'] == $value) {
						$isDel = 'no';
					}
		        }

		        if ($isDel == 'yes') {
		        	$file_path = _IMGS_PATH_ . $list[$i]['path'];
					if (file_exists($file_path)) {
						unlink($file_path);
					}

					//删除该图片对应的数据库记录
					$rst->addCollect('id', $list[$i]['id']);
					$rst->deleteInfo('housecraftpic');
		        }
			}

			//保存新的详情大图
	        $tempPicPath = array();
	        foreach ($bigPicList as $value) {
	        	$tempPath = '';
	        	if (strpos($value, ';base64,')) {
	        		$tempPath = 'upload/housecraft/samplepic/' . util::getFileName($value);
		            util::saveFile($value, _IMGS_PATH_ . $tempPath);
		            $tempPicPath[] = $tempPath;
	        	}
	        }

	        //保存图片记录
	        for ($i = 0; $i < count($tempPicPath); $i++) {
	        	$rst->addCollect('housecraftid', $uuid);
	        	$rst->addCollect('path', $tempPicPath[$i]);
	        	$rst->addCollect('sx', $i + 1);
	        	$rst->insertInfo('housecraftpic');
	        }

	        //保存信息
			$rst->addCollect('title', getPost('title'));
			$rst->addCollect('sortation', getPost('sortation'));
			$rst->addCollect('address', getPost('address'));
			$rst->addCollect('position', getPost('position'));
			$rst->addCollect('person', getPost('person'));
			$rst->addCollect('phone', getPost('phone'));
			$rst->addCollect('identity', getPost('identity'));
			$rst->addCollect('feature', $feature);
			$rst->addCollect('area', getPost('area'));
			$rst->addCollect('introduce', $introducePath);
			$rst->addCollect('smallpic', $smallPath);
			$rst->addCollect('remark', getPost('remark'));
			$rst->addCollect('housecraftid', $uuid);
			$rst->updateInfo('housecraft');
		}

		$result = util::getSuccess('success');
	    $result['housecraftid'] = $uuid;
		return $result;
	}

	//给家政服务信息重新排序
	public function resetSequence() {
		$rst = new sqlcon();
		$rst->setSql('update housecraft set sort = rand() * 25 where status = 1');
		$rst->execute();

		return util::getSuccess('success');
	}

	//发布家政服务信息
	public function putHousecraft() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();
		$rst->addCollect('status', '1');
		$rst->addCollect('housecraftid', getPost('housecraftid'));
		$rst->updateInfo('housecraft');

		return util::getSuccess('success');
	}

	//下架家政服务信息
	public function pullHousecraft() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();
		$rst->addCollect('status', '2');
		$rst->addCollect('housecraftid', getPost('housecraftid'));
		$rst->updateInfo('housecraft');

		return util::getSuccess('success');
	}

	//回收家政服务信息
	public function retrieveHousecraft() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();
		$rst->addCollect('status', '3');
		$rst->addCollect('housecraftid', getPost('housecraftid'));
		$rst->updateInfo('housecraft');

		return util::getSuccess('success');
	}

	//恢复家政服务信息（将状态从回收恢复为待审核）
	public function restoreHousecraft() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();
		$rst->addCollect('status', '0');
		$rst->addCollect('housecraftid', getPost('housecraftid'));
		$rst->updateInfo('housecraft');

		return util::getSuccess('success');
	}

	//置顶家政服务信息
	public function topHousecraft() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();
		$rst->addCollect('istop', '1');
		$rst->addCollect('toptype', getPost('toptype'));
		$rst->addCollect('refreshtime', date('Y-m-d H:i:s'));
		$rst->addCollect('topstarttime', date('Y-m-d H:i:s'));
		$rst->addCollect('topendtime', getPost('topendtime') . ' ' . date('H:i:s'));
		$rst->addCollect('housecraftid', getPost('housecraftid'));
		$rst->updateInfo('housecraft');

		return util::getSuccess('success');
	}

	//重新发布家政服务信息
	public function putHousecraftAgain() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();
		$rst->addCollect('istop', '0');
		$rst->addCollect('toptype', '0');
		$rst->addCollect('refreshcount', '0');
		$rst->addCollect('isautorefresh', '0');
		$rst->addCollect('status', getPost('status'));
		$rst->addCollect('sort', '0');
		$rst->addCollect('clicktime', '');
		$rst->addCollect('dialtime', '');
		$rst->addCollect('refreshtime', date('Y-m-d H:i:s'));
		$rst->addCollect('expiretime', getPost('expiretime') . ' ' . date('H:i:s'));
		$rst->addCollect('topstarttime', '');
		$rst->addCollect('topendtime', '');
		$rst->addCollect('housecraftid', getPost('housecraftid'));
		$rst->updateInfo('housecraft');

		return util::getSuccess('success');
	}

	//删除家政服务信息
	public function deleteHousecraft() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();
		$info = $rst->getInfo('smallpic, introduce', 'housecraft', "housecraftid = '" . getPost('housecraftid') . "'");
		if (empty($info)) {
			return util::getDataError('信息不存在');
		}

		//删除服务详情文件
		if (!empty($info['introduce'])) {
			$file_path = _FILE_PATH_ . $info['introduce'];
			if (file_exists($file_path)) {
				unlink($file_path);
			}
		}

		//删除展示图
		if (!empty($info['smallpic'])) {
        	$file_path = _IMGS_PATH_ . $info['smallpic'];
			if (file_exists($file_path)) {
				unlink($file_path);
			}
        }

        //删除环境图及记录
        $list = $rst->getList('path', 'housecraftpic', "housecraftid = '" . getPost('housecraftid') . "'");
		for ($i = 0; $i < count($list); $i++) {
			if (!empty($list[$i]['path'])) {
	        	$file_path = _IMGS_PATH_ . $list[$i]['path'];
				if (file_exists($file_path)) {
					unlink($file_path);
				}
	        }
		}
		$rst->addCollect('housecraftid', getPost('housecraftid'));
		$rst->deleteInfo('housecraftpic');

		//删降家政服务信息
		$rst->addCollect('housecraftid', getPost('housecraftid'));
		$rst->deleteInfo('housecraft');

		return util::getSuccess('success');
	}

	//获取家政服务信息（查看详情页使用）
	public function getHousecraftInfo() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();
		$permission = getPost('permission');

		$info = $rst->getInfo('*', 'housecraft', "housecraftid = '" . getPost('housecraftid') . "'");
		if (empty($info)) {
			return util::getDataError('信息不存在');
		}

		//获取服务详情
		if (!empty($info['introduce'])) {
			$file_path = _FILE_PATH_ . $info['introduce'];
			$info['introduce'] = util::readFile($file_path);
			if (!empty($info['introduce'])) {
                $info['introduce'] = nl2br($info['introduce']);
            }
		}

		$nowtime = strtotime(date('Y-m-d H:i:s'));
		//计算展示剩余天数
		$day = 0;
		$expiretime = strtotime($info['expiretime']);
    	$seconds = $expiretime - $nowtime;
    	if ($seconds >= 0) {
    		$day = $seconds / 60 / 60 / 24;
    	}
    	$info['showResidueDays'] = intval($day);

    	//计算置顶剩余天数
    	$day = 0;
		if ($info['istop'] == '1') {
			$topendtime = strtotime($info['topendtime']);
			$seconds = $topendtime - $nowtime;
			if ($seconds >= 0) {
        		$day = $seconds / 60 / 60 / 24;
        	}
		}
		$info['topResidueDays'] = intval($day);

		//格式化到期时间
		if ($info['expiretime'] > '2034-01-01 00:00:00') {
			$info['expiretime'] = '永久显示';
		}

		//获取商家图片
		$picList = $rst->getList('path', 'housecraftpic', "housecraftid = '" . getPost('housecraftid') . "'", 'sx asc');
		for ($i = 0; $i < count($picList); $i++) {
			$picList[$i]['name'] = time() . $i;
			$picList[$i]['path'] = _HTTP_PATH_ . $picList[$i]['path'];
		}
		$info['picList'] = $picList;

		//获取商家认证信息
		$verify = $rst->getInfo('*', 'verify', "verifyid = '" . $info['company_verifyid'] . "'");
		if (!empty($verify)) {
			//格式化营业执照图片
			$verify['pic'] = _HTTP_PATH_ . $verify['pic'];
			
			$info['companyVerify'] = $verify;
		}

		$result = util::getSuccess('success');
		$result['housecraftInfo'] = $info;
		if ($permission == 'yes') {
	    	$result['permission'] = util::getOperateItem(getPost('menuid'));
	    }
		return $result;
	}

	//获取家政服务信息（编辑页使用）
	public function getHousecraftInfo2() {
		if (empty(getPost('housecraftid'))) {
			return util::getValidError('ID格式错误');
		}

		$rst = new sqlcon();

		$info = $rst->getInfo('*', 'housecraft', "housecraftid = '" . getPost('housecraftid') . "'");
		if (empty($info)) {
			return util::getDataError('信息不存在');
		}

		//获取服务详情
		if (!empty($info['introduce'])) {
			$file_path = _FILE_PATH_ . $info['introduce'];
			$info['introduce'] = util::readFile($file_path);
		}

		//格式化列表小图路径
		if (!empty($info['smallpic'])) {
			$info['smallpic'] = _HTTP_PATH_ . $info['smallpic'];
		}

		//获取商家图片
		$picList = $rst->getList('path', 'housecraftpic', "housecraftid = '" . getPost('housecraftid') . "'", 'sx asc');
		for ($i = 0; $i < count($picList); $i++) {
			$picList[$i]['name'] = time() . $i;
			$picList[$i]['path'] = _HTTP_PATH_ . $picList[$i]['path'];
		}
		$info['picList'] = $picList;

		$result = util::getSuccess('success');
		$result['housecraftInfo'] = $info;
		return $result;
	}
	
}